import fs from 'node:fs'
import _ from 'lodash'
import YAML from 'yaml'
import chokidar from 'chokidar'
import {createPicture} from '../src/img/createPicture.js'
import { basename, resolve } from "path";
import path from "path";
export const DirPath = resolve(process.cwd(), "./plugins/Mini-world-plugin");
export const AppName = basename(DirPath);
class RConfig {
  constructor () {
    // 配置文件
      this.configPath = './plugins/Mini-world-plugin/configs/'
    this.config = {}

    // 监听文件
    this.watcher = { config: {} }
  }

  /**
   * 获取配置文件
   * @param name
   * @returns {any}
   */
  getConfig (name) {
    let ignore = []

    if (ignore.includes(`${name}`)) {
      return this.getYaml(name)
    }

    return this.getYaml(name)
  }

  /**
   * 获取配置yaml
   * @param name 名称
   */
  getYaml (name) {
    // 获取文件路径
    let file = this.getFilePath(name)
    // 解析xml
    const yaml = YAML.parse(fs.readFileSync(file, 'utf8'))
    // 监听文件
    this.watch(file, name)
    return yaml
  }

  /**
   * 获取文件路径
   * @param name
   * @returns {string}
   */
  getFilePath (name) {
    return `${this.configPath}${name}.yaml`
  }

  /**
   * 听配置文件
   * @param file
   * @param name
   */
// 监听文件变化，当文件发生变化时，删除logger中的mark
  watch (file, name) {
    const watcher = chokidar.watch(file)

    watcher.on('change', (path) => {
      delete
      logger.mark(`[修改配置文件][${name}]`)
    })
  }

  /**
   * 保存配置
   * @param name
   * @param data
   */
// 保存设置
  saveSet (name, data) {
    // 获取文件路径
    let file = this.getFilePath(name)
    // 如果数据为空，判断文件是否存在，如果存在则删除
    if (_.isEmpty(data)) {
      fs.existsSync(file) && fs.unlinkSync(file)
    } else {
      // 将数据转换为YAML格式
      let yaml = YAML.stringify(data)
      // 将数据写入文件
      fs.writeFileSync(file, yaml, 'utf8')
    }
  }
}

export default new RConfig()


/**
 * @param directory 文件
 * @param data 数据
 * @returns
 */
export async function oImages(directory, data = {}) {
  // 创建截图工具
  const img = await createPicture({
    AppName,
    tplFile: `${DirPath}${directory}`,
    data,
    SOptions: { type: 'jpeg', quality: 100 }
  }).catch(err => {
    console.log(err)
    return false
  })
  if (typeof img == 'boolean') return '💥了，生成图片失败，等待修复...'
  return img
}
export const _PATH = {
  shop: path.join(DirPath,'resource','data','item','shop.json'),
  player_path: path.join(DirPath,'resource','data','player')
}
let jsontype = {
  1:  _PATH.shop
}

/**
 *
 * @param num []
 * @param
 * @returns
 */
export async function Read_json(num, ...paths) {
  const jsonType = jsontype[num]
  let playerPath = await buildPath(jsonType, paths)
  try {
    const playerData = fs.readFileSync(playerPath, 'utf8')
    const player = JSON.parse(playerData)
    return player
  } catch (err) {
    console.log(err)
    return 'error'
  }
}


export async function buildPath(
  jsonType,
  paths
) {
  let playerPath = jsonType
  if (paths.length > 0) {
    playerPath += paths.join('')
  }
  return path.join(playerPath)
}

/**
 * 检测路径是否存在
 * @param usr_qq 用户qq号，用于判定用户的json文件是否存在
 * @return 存在路径则返回true，否则false
 */
export async function existplayer(usr_qq) {
  let exist_player
  exist_player = fs.existsSync(`${_PATH.player_path}/${usr_qq}.json`)
  if (exist_player) {
    return true
  }
  return false
}


/**
 * 读取存档信息，返回成一个JavaScript对象
 * @param usr_qq 传入对应用户的qq号
 * @return player 数组形式的数据
 */
export async function Read_player(usr_qq) {
  let dir = path.join(`${_PATH.player_path}/${usr_qq}.json`)
  try {
    let player = fs.readFileSync(dir, 'utf8');
      //将字符串数据转变成数组格式
    player = JSON.parse(decodeURIComponent(player));
    return player;
  } catch (err) {
    console.log(err);
    return 'error';
  }
}


/**
 * 写入存档信息,第二个参数是一个JavaScript对象
 * @param usr_qq 用户qq号
 * @param player JavaScript对象
 * @return 完成写入操作，无返回
 */
export async function Write_player(usr_qq, player) {
  let dir = path.join(_PATH.player_path, `${usr_qq}.json`)
  let new_ARR = JSON.stringify(player, '', '\t')
  fs.writeFileSync(dir, new_ARR, 'utf8', (err) => {
    console.log('写入成功', err)
  })
  return
}
